package com.sfexpress.mycatweb.service.monitor;

import java.util.Random;

import org.springframework.stereotype.Service;

import com.sfexpress.mycatweb.entity.monitor.JvmCpuStat;
import com.sfexpress.mycatweb.entity.monitor.JvmHeapStat;
import com.sfexpress.mycatweb.entity.monitor.JvmMonitorInfo;

@Service
public class MockJvmMonitorService implements JvmMonitorService {

	@Override
	public JvmMonitorInfo getJvmMonitorInfo() throws Exception {
		
		JvmMonitorInfo jvmInfo = new JvmMonitorInfo();
		jvmInfo.setCpuStat(mockJvmCpuStat());
		jvmInfo.setHeapStat(mockJvmHeapStat());
		
		return jvmInfo;
	}
	
	/**
	 * mock采集jvm cpu状态信息
	 * @return
	 */
	private JvmCpuStat mockJvmCpuStat() {
		
		Random rand = new Random(System.currentTimeMillis());
		int ratio = rand.nextInt(100);
		
		JvmCpuStat jvmCpuStat = new JvmCpuStat();
		jvmCpuStat.setUsed(ratio);
		
		return jvmCpuStat;
	}
	
	/**
	 * mock采集jvm heap状态信息
	 * @return
	 */
	private JvmHeapStat mockJvmHeapStat() {
		
		Runtime rt = Runtime.getRuntime();
		long total = rt.totalMemory();
		long free = rt.freeMemory();
		long max = rt.maxMemory();
		
		JvmHeapStat jvmHeapStat = new JvmHeapStat();
		jvmHeapStat.setTotal(total);
		jvmHeapStat.setUsed(total - free);
		jvmHeapStat.setMax(max);
		
		return jvmHeapStat;
	}

}
